package logic

import (
	"context"
	"encoding/json"
	"product_zc/models/cache"
	"product_zc/models/mysql"
	"time"

	"product_zc/productRpc/internal/svc"
	"product_zc/productRpc/productRpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type ProductHotListLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewProductHotListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ProductHotListLogic {
	return &ProductHotListLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *ProductHotListLogic) ProductHotList(in *productRpc.ProductHotListRequest) (*productRpc.ProductHotListResponse, error) {
	// todo: add your logic here and delete this line

	var products []mysql.Product
	cacheData, _ := cache.Rdb.Get(l.ctx, "productHotList").Result()

	if cacheData == "" {

		mysql.DB.Debug().Limit(20).
			Order("browse_number desc").Find(&products)

		marshal, _ := json.Marshal(products)
		cache.Rdb.Set(l.ctx, "productHotList", marshal, time.Hour*24)
	} else {
		json.Unmarshal([]byte(cacheData), &products)
	}

	var productsHotList []*productRpc.ProductHotList
	for _, product := range products {
		list := productRpc.ProductHotList{
			Id:           int64(product.ID),
			Title:        product.Title,
			Price:        float32(product.Price),
			BrowseNumber: product.BrowseNumber,
			UserId:       product.UserId,
		}

		productsHotList = append(productsHotList, &list)
	}
	return &productRpc.ProductHotListResponse{
		List: productsHotList,
	}, nil
}
